package cn.tedu.jdbc;

import cn.tedu.jdbc.utils.DbUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 使用PreparedStatement完成分页查询
 */
public class JDBCTest16 {
    public static void main(String[] args) {
        /**
         * 需求：查询所有员工姓名，每页显示3条（pageSize）、显示第2页(pageNo).
         */
        //每页显示的条数
        int pageSize = 3;
        //显示第几页
        int pageNo = 2;

        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
//第pageNo页：limit（pageNo - 1）*pageSize，pageSize
        try {
            conn = DbUtils.getConnection();
            String sql = "select ename from emp limit ?, ?";
            ps = conn.prepareStatement(sql);
            ps.setInt(1,(pageNo - 1) * pageSize);
            ps.setInt(2,pageSize);
            rs = ps.executeQuery();
            while(rs.next()){
                String ename = rs.getString("ename");
                System.out.println(ename);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DbUtils.close(conn,ps,rs);
        }

    }
}
